package com.it.androidCommonUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utlis {

	
	
	/**
	 * 
	 * @param string
	 * @return utf-8的编码
	 * 
	 */
		public static String stringToMD5(String string) {  
		  
		 return  stringToMD5(string, "UTF-8");
		 
		} 

		public static String stringToMD5(String string,String charset) {  
		    byte[] hash;  
		  
		    try {  
		        hash = MessageDigest.getInstance("MD5").digest(string.getBytes(charset));  
		        StringBuilder hex = new StringBuilder(hash.length * 2);  
			    for (byte b : hash) {  
			        if ((b & 0xFF) < 0x10)  
			            hex.append("0");  
			        hex.append(Integer.toHexString(b & 0xFF));  
			    }  
			  
			    return hex.toString(); 
		    
		    
		    } catch (NoSuchAlgorithmException e) {  
		        e.printStackTrace();  
		        return null;  
		    } catch (UnsupportedEncodingException e) {  
		        e.printStackTrace();  
		        return null;  
		    }  
		  
		 
		}
	
		// 计算文件的 MD5 值
	    public static String md5(File file) {
	        if (file == null || !file.isFile() || !file.exists()) {
	            return "";
	        }
	        FileInputStream in = null;
	        String result = "";
	        byte buffer[] = new byte[8192];
	        int len;
	        try {
	            MessageDigest md5 = MessageDigest.getInstance("MD5");
	            in = new FileInputStream(file);
	            while ((len = in.read(buffer)) != -1) {
	                md5.update(buffer, 0, len);
	            }
	            byte[] bytes = md5.digest();

	            for (byte b : bytes) {
	                String temp = Integer.toHexString(b & 0xff);
	                if (temp.length() == 1) {
	                    temp = "0" + temp;
	                }
	                result += temp;
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }finally {
	            if(null!=in){
	                try {
	                    in.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return result;
	    }
	
	
}
